<?php

namespace humhub\modules\api\controllers;

use humhub\modules\api\models\Scores;
use Yii;
use humhub\modules\comment\models\Comment;
use yii\web\HttpException;
use humhub\modules\post\models\Post;
use humhub\modules\api\models\TaskUser;

use humhub\modules\api\models\TaskJob;
use humhub\modules\space\models\Space;

use yii\filters\auth\CompositeAuth;
use yii\filters\auth\HttpBearerAuth;

/**
 * 任务的: 获取, 发布, 编辑, 删除
 */
class TaskjobController extends Base3Controller
{

    /**
     * @inheritdoc
     */
    public function init(){
        $_GET['contentModel'] =  'humhub\modules\post\models\Post';
        $_POST['contentModel'] =  'humhub\modules\post\models\Post';
        parent::init();
    }

    /**
     * @inheritdoc
     */
    public function behaviors(){
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => CompositeAuth::className(),
            'authMethods' => [
                //QueryParamAuth::className(),
                HttpBearerAuth::className(),
            ],
        ];

        $behaviors['acl'] = [
            'class' => \humhub\components\behaviors\AccessControl::className(),
            'guestAllowedActions' => ['show']
        ];

        return $behaviors;
    }

    /**
     * @inheritdoc
     */
    public function actions(){
        $actions = parent::actions();
        unset($actions['update'], $actions['create'], $actions['index'], $actions['delete']);
        return $actions;
    }

    /**
     * 获取提交过的任务结果(附件)列表
     *
     * GET /api/taskjob
     *
     * get.contentId 内容ID
     *
     * get.contentModel 固定值=[post]
     *
     * get.uid 用户uid，过滤指定用户的列表（用于显示某用户的任务结果列表）
     *
     * @return array 部分属性说明:(message评论内容, user发布评论的用户, created_at评论时间) 
     * - is_score   =1/0=是/否评分
     * - is_reward  =1/0=是/否奖励
     * - 增加返回 count = 提交作业人数（非数据总条数)
     */
    public function actionShow(){
        $content = $this->parentContent;

        //$pagination = new \yii\data\Pagination([
        //    'totalCount' => TaskJob::GetJobCount($content->className(), $content->getPrimaryKey()),
        //    'pageSize' => 10, //$this->module->commentsBlockLoadSize
        //]);
        $pagination = new \yii\data\Pagination([
            'defaultPageSize' => 10,
            'validatePage' => false,
        ]);

        $where = [
            'task_job.object_model' => $content->className(),
            'task_job.object_id' => $content->getPrimaryKey(),
        ];
        $uid = (int)Yii::$app->request->get('uid');
        if( $uid ){
            $where['task_job.created_by'] = $uid;
        }

        $where['task_user.status'] = 1;

        $query = TaskJob::find();
        $query->leftJoin('task_user', 'task_user.task_id=task_job.object_id AND task_user.created_by=task_job.created_by');
        $query->where($where);
        $query->offset($pagination->offset)->limit($pagination->limit);
        $query->orderBy('task_job.created_at DESC');
        //$comments = array_reverse($query->all());
        //echo $query->createCommand()->getRawSql();exit;//sql
        $comments = $query->all();

        $output = array();
        foreach ($comments as $comment) {
            $user['displayname'] = $comment->user->displayName;
            $user['guid']        = $comment->user->guid;
            $user['image']       = $comment->user->getProfileImage()->getUrl();

            $_cm = $comment->attributes;
            $cm['id']        = $_cm['id'];
            $cm['message']   = $_cm['message'];
            $cm['object_id'] = $_cm['object_id'];
            $cm['is_score']  = $_cm['score']?1:0;
            $cm['is_reward'] = $_cm['reward']?1:0;

            /*
            $cm['comment']   = $_cm['comment'];
            $cm['rewardimg'] = $_cm['rewardimg'];
            if( $_cm['rewardimg'] ){
                $_file = \humhub\modules\file\models\File::findOne(['guid' => $_cm['rewardimg']]);
                if( $_file ){
                    if ($_file->getMimeBaseType() == "image"){
                        $cm['rewardimg'] = $_file->getUrl();
                    }
                }
            }
             */

            $cm['created_at']= $_cm['created_at'];
            $cm['created_by']= $_cm['created_by'];
            $cm['updated_at']= $_cm['updated_at'];
            $cm['updated_by']= $_cm['updated_by'];
            $cm['user'] = $user;
            //$cm['canWrite'] = $comment->canWrite();
            //$cm['canDelete'] = $comment->canDelete();

            //Files
            if ($comment->isNewRecord && $comment->getRelation('content', false) !== null) {
                $files = \humhub\modules\file\models\File::findAll(['guid' => array_map('trim', explode(',', $comment->content->attachFileGuidsAfterSave))]);
            } else {
                $files = \humhub\modules\file\models\File::getFilesOfObject($comment);
            }
            /*
            $cm['image'] = [];
            foreach ($files as $file){
                if ($file->getMimeBaseType() == "image"){
                    $cm['image'][] = $file->getPreviewImageUrl(200, 200);
                }
            }
             */
            $cm['files'] = [];
            foreach ($files as $file){
                //if ($file->getMimeBaseType() == "image")
                //    continue;
                $f['url'] = $file->getUrl();
                $f['name'] = $file->file_name;
                $f['size'] = $file->size; //Yii::$app->formatter->asSize($file->size);
                $cm['files'][] = $f;
            }

            $output[] = $cm;
        }

        $totalCount = TaskUser::GetJobCount([
            'task_id'=> $content->getPrimaryKey(),
            'status' => 1,
        ]);

        return [
            'count' => $totalCount,
            'lists' => $output,
        ];
        return $output;
    }

    /**
     * 获取指定作业的详情
     *
     * GET /api/taskjob/info
     *
     * get.contentId 内容ID
     *
     * get.contentModel 固定值=[post]
     *
     * get.id 指定作业的id (如果id赋值，则uid传值无效)
     *
     * get.uid 用户uid，过滤指定用户的单个作业
     *
     * @return array 部分属性参考 api/taskjob
     * - is_score   =1/0=是/否评分
     * - is_reward  =1/0=是/否奖励
     * - score   评分。10分制即2分=1星，若=NULL则未评分
     * - comment 评语。
     * - reward  奖励内容。
     * - rewardimg 奖励图片。
     */
    public function actionInfo(){
        $content = $this->parentContent;

        $id = (int)Yii::$app->request->get('id');
        if( $id ){
            $where['id'] = $id;
        }else{
            $postid = (int)Yii::$app->request->get('contentId');
            $uid = (int)Yii::$app->request->get('uid');
            $where['created_by'] = $uid;
            $where['object_id']  = $postid;
        }
        $query = TaskJob::find();
        $query->where($where);
        //$comments = $query->all();
        $comment = $query->one();

        $output = array();
        //foreach ($comments as $comment) 
        if ($comment) 
        {
            $_cm = $comment->attributes;

            if( ! $_cm['visibility'] ){
                $s = 0;
                $space = $this->getspace($_cm['object_id']);
                if( ! (Yii::$app->user->id==$_cm['created_by'] || Yii::$app->user->id==$space->created_by) ){
                    throw new HttpException(403, '作业仅导师可见.');
                }
            }

            $user['displayname'] = $comment->user->displayName;
            $user['guid'] = $comment->user->guid;
            $user['image'] = $comment->user->getProfileImage()->getUrl();

            $cm['id']        = $_cm['id'];
            $cm['message']   = $_cm['message'];
            $cm['object_id'] = $_cm['object_id'];
            $cm['visibility']= $_cm['visibility'];
            $cm['is_score']  = $_cm['score']?1:0;
            $cm['is_reward'] = $_cm['reward']?1:0;
            $cm['score']     = $_cm['score'];
            $cm['comment']   = $_cm['comment'];
            $cm['reward']    = $_cm['reward'];

            $cm['rewardimg'] = $_cm['rewardimg'];
            if( $_cm['rewardimg'] ){
                $_file = \humhub\modules\file\models\File::findOne(['guid' => $_cm['rewardimg']]);
                if( $_file ){
                    if ($_file->getMimeBaseType() == "image"){
                        $cm['rewardimg'] = $_file->getUrl();
                    }
                }
            }

            $cm['created_at']= $_cm['created_at'];
            $cm['updated_at']= $_cm['updated_at'];
            $cm['user'] = $user;
            //$cm['canWrite'] = $comment->canWrite();
            //$cm['canDelete'] = $comment->canDelete();

            //Files
            if ($comment->isNewRecord && $comment->getRelation('content', false) !== null) {
                $files = \humhub\modules\file\models\File::findAll(['guid' => array_map('trim', explode(',', $comment->content->attachFileGuidsAfterSave))]);
            } else {
                $files = \humhub\modules\file\models\File::getFilesOfObject($comment);
            }
            /*
            $cm['image'] = [];
            foreach ($files as $file){
                if ($file->getMimeBaseType() == "image"){
                    $cm['image'][] = $file->getPreviewImageUrl(200, 200);
                }
            }
             */
            $cm['files'] = [];
            foreach ($files as $file){
                //if ($file->getMimeBaseType() == "image")
                //    continue;
                $f['url'] = $file->getUrl();
                $f['name'] = $file->file_name;
                $f['size'] = $file->size; //Yii::$app->formatter->asSize($file->size);
                $cm['files'][] = $f;
            }

            $output[] = $cm;
        }

        return $output;
    }


    /**
     * 更新任务进度(传参类似评论接口)
     *
     * POST /api/taskjob
     *
     * post.contentId 内容post的id
     *
     * post.contentModel 固定值=[post]
     *
     * post.message  评论内容
     *
     * post.visibility =1所有人可见; =0仅导师可见
     *
     * post.fileList 上传文件，值为文件的guid，每个guid需以逗号[,]开头
     *
     * @return array 评论的id信息
     */
    public function actionCreate(){
        $this->forcePostRequest();

        if (Yii::$app->user->isGuest) {
            throw new HttpException(403, '任务更新失败.');
        }
        
        if (!Yii::$app->getModule('comment')->canComment($this->parentContent->content)) {
            throw new HttpException(403, '任务更新失败.');
        }

        $postid = (int)Yii::$app->request->post('contentId');
        $post = Post::findOne( $postid );
        if( ! $post ){
            throw new HttpException(500, '无效的任务.');
        }
        //Task
        if( $post->p_type != 1 ){
            throw new HttpException(500, '无效的任务.');
        }

        //获取Post所属Space
        $activeQuery = \humhub\modules\content\models\WallEntry::find();
        $activeQuery->joinWith('content');
        $activeQuery->leftJoin('post', 'content.object_id=post.id AND content.object_model=:postModel', ['postModel' => \humhub\modules\post\models\Post::className()]);
        $activeQuery->andWhere(['!=', 'content.object_model', \humhub\modules\activity\models\Activity::className()]);
        $activeQuery->andWhere("post.id=".$postid);
        $wallEntry = $activeQuery->one();
        //echo $activeQuery->createCommand()->getRawSql();exit;

        $underlyingObject = $wallEntry->content->getPolymorphicRelation();
        if ( !($underlyingObject->content->container instanceof Space) ){
            throw new HttpException(500, '无效的任务.');
        }
        //任务周期
        $space = $underlyingObject->content->container;
        if( $space->s_t2 < time() ){
            throw new HttpException(500, '任务已过期.');
        }
        $myuid   = Yii::$app->user->id;

        //add task user
        $taskUser = TaskUser::findOne(['task_id'=>$postid, 'user_id'=>$myuid]);
        if( $taskUser === null ){
            $taskUser = new TaskUser();
            $taskUser->user_id  = $myuid;
            $taskUser->task_id  = $postid;
            $taskUser->space_id = $space->id;
            if( ! $taskUser->save() ){
                throw new HttpException(403, '任务更新失败.');
            }
        }

        //add task job
        $message = Yii::$app->request->post('message');
        $files = Yii::$app->request->post('fileList');
        if (trim($message) === '' && trim($files) === '') {
            // do not create empty comments
            Yii::$app->params['res-success'] = false;
            return false;
        }

        $comment = new TaskJob();
        $comment->message = $message;
        $comment->visibility= (Yii::$app->request->post('visibility')==1)?1:0;
        $comment->object_model = $this->parentContent->className();
        $comment->object_id = $this->parentContent->getPrimaryKey();
        $comment->save();
        $scores=new Scores();
        $scores->setScores('提交作业',5);

        \humhub\modules\file\models\File::attachPrecreated($comment, $files);

        // Reload comment to get populated created_at field
        $comment->refresh();

        if( $comment ){
            $taskUser->cmnums = new \yii\db\Expression('COALESCE(cmnums, 0) + 1');
            $taskUser->save();
            return $comment;
        }
        Yii::$app->params['res-success'] = false;
        return false;
    }

    /**
     * 导师评分
     *
     * POST /api/taskjob/score
     *
     * post.contentId 内容post的id
     *
     * post.contentModel 固定值=[post]
     *
     * post.id 作业的ID值
     *
     * post.score 分数：1-10
     *
     * post.comment  评语
     *
     * @return array 评论的id信息
     */
    public function actionScore(){
        $this->forcePostRequest();

        if (Yii::$app->user->isGuest) {
            throw new HttpException(403, '作业评价失败.');
        }
        
        if (!Yii::$app->getModule('comment')->canComment($this->parentContent->content)) {
            throw new HttpException(403, '作业评价失败.');
        }

        $postid = (int)Yii::$app->request->post('contentId');
        $post = Post::findOne( $postid );
        if( ! $post ){
            throw new HttpException(500, '无效的任务.');
        }
        //Task
        if( $post->p_type != 1 ){
            throw new HttpException(500, '无效的任务.');
        }

        $space = $this->getspace($postid);
        if( $space->created_by != Yii::$app->user->id ){
            throw new HttpException(500, '操作异常.');
        }

        //add task job
        $py = Yii::$app->request->post('comment');
        if (trim($py) == '' ) {
            throw new HttpException(500, '评语不能为空.');
        }
        $score = (int)Yii::$app->request->post('score');
        if ($score<1 || $score>10 ) {
            throw new HttpException(500, '评分不能为0分.');
        }

        $id = (int)Yii::$app->request->post('id');
        $comment = TaskJob::findOne($id);
        if( ! $comment ){
            throw new HttpException(500, '作业异常.');
        }
        if( $comment->score ){
            throw new HttpException(500, '作业已评论.');
        }
        $scores=new Scores();
        $jf=$score*10;
        $scores->setScores('导师积分奖励',$jf);
        $comment->score  = $score;
        $comment->comment= $py;
        $comment->save();
        // Reload comment to get populated created_at field
        $comment->refresh();
        return $comment;
    }

    /**
     * 导师奖励
     *
     * POST /api/taskjob/reward
     *
     * post.contentId 内容post的id
     *
     * post.contentModel 固定值=[post]
     *
     * post.id 作业的ID值
     *
     * post.reward 奖励内容
     *
     * post.rewardimg 奖励图片的guid
     *
     * @return array 评论的id信息
     */
    public function actionReward(){
        $this->forcePostRequest();

        if (Yii::$app->user->isGuest) {
            throw new HttpException(403, '作业评价失败.');
        }
        
        if (!Yii::$app->getModule('comment')->canComment($this->parentContent->content)) {
            throw new HttpException(403, '作业评价失败.');
        }

        $postid = (int)Yii::$app->request->post('contentId');
        $post = Post::findOne( $postid );
        if( ! $post ){
            throw new HttpException(500, '无效的任务.');
        }
        //Task
        if( $post->p_type != 1 ){
            throw new HttpException(500, '无效的任务.');
        }

        $space = $this->getspace($postid);
        if( $space->created_by != Yii::$app->user->id ){
//            throw new HttpException(500, '操作异常.');
        }

        //add task job
        $py = Yii::$app->request->post('reward');
        if (trim($py) == '' ) {
            throw new HttpException(500, '评语不能为空.');
        }
        $pyimg = Yii::$app->request->post('rewardimg');

        $id = (int)Yii::$app->request->post('id');
        $comment = TaskJob::findOne($id);
        if( ! $comment ){
            throw new HttpException(500, '作业异常.');
        }
        if( $comment->reward ){
            throw new HttpException(500, '作业已奖励.');
        }
        $comment->reward    = $py;
        $comment->rewardimg = $pyimg;
        $comment->save();
        // Reload comment to get populated created_at field
        $comment->refresh();
        return $comment;
    }
    private function getspace($postid){
        //获取Post所属Space
        $activeQuery = \humhub\modules\content\models\WallEntry::find();
        $activeQuery->joinWith('content');
        $activeQuery->leftJoin('post', 'content.object_id=post.id AND content.object_model=:postModel', ['postModel' => \humhub\modules\post\models\Post::className()]);
        $activeQuery->andWhere(['!=', 'content.object_model', \humhub\modules\activity\models\Activity::className()]);
        $activeQuery->andWhere("post.id=".$postid);
        $wallEntry = $activeQuery->one();

        $underlyingObject = $wallEntry->content->getPolymorphicRelation();
        if ( !($underlyingObject->content->container instanceof Space) ){
            throw new HttpException(500, '系统繁忙.');
        }
        $space = $underlyingObject->content->container;
        return $space;
    }
}
